package com.zzr.zzrbackend.service.Impl;

import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.TeaException;
import com.zzr.zzrbackend.config.JwtInterceptor;
import com.zzr.zzrbackend.constant.Constant;
import com.zzr.zzrbackend.mapper.*;
import com.zzr.zzrbackend.pojo.domain.*;
import com.zzr.zzrbackend.pojo.dto.CommonResult;
import com.zzr.zzrbackend.pojo.dto.param.SingleTrackMessageParam;
import com.zzr.zzrbackend.pojo.dto.param.TrackMessageParam;
import com.zzr.zzrbackend.pojo.dto.result.*;
import com.zzr.zzrbackend.service.TrackRecordService;
import com.zzr.zzrbackend.util.TimeUtil;
import com.zzr.zzrbackend.util.TokenUtils;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;


@Service
@Slf4j
public class TrackRecordServiceImpl implements TrackRecordService {
    @Resource
    UserMapper userMapper;
    @Resource
    private JwtInterceptor jwtInterceptor;
    @Resource
    HttpServletRequest request;
    @Resource
    DisabuseRecordMapper disabuseRecordMapper;
    @Resource
    TrackRecordTimeMapper trackRecordTimeMapper;
    @Resource
    HomeInterfaceMapper homeInterfaceMapper;
    @Resource
    RelationMapper relationMapper;

    @Override
    public CommonResult<TrackRecordScheduleResult> schedule() {

        Integer childId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(childId);
        if (user == null) {
            return CommonResult.fail("数据库异常");
        }

        //疑惑的时间列表
        List<DisabuseRecord> disabuseRecordList = disabuseRecordMapper.selectDisabuseListByChildId(childId);
        if (disabuseRecordList.size() == 0) {
            return CommonResult.fail("数据库异常");
        }

        List<Long> timeSchedule = new ArrayList<>();
        HashSet<String> hs = new HashSet<>();
        for (DisabuseRecord temp : disabuseRecordList) {
            long time = temp.getTime();
            String day = TimeUtil.transform(time);
            hs.add(day);
        }

        //听书的时间列表
        List<TrackRecordTime> trackRecordTimeList = trackRecordTimeMapper.selectByUserId(childId);
        if (trackRecordTimeList.size() == 0) {
            return CommonResult.fail("数据库异常");
        }
        for (TrackRecordTime temp : trackRecordTimeList) {
            long time = temp.getTime();
            String day = TimeUtil.transform(time);
            hs.add(day);
        }
        for (String day : hs) {
            Long time = TimeUtil.transformTurnAll(day);
            timeSchedule.add(time);
        }

        TrackRecordScheduleResult trackRecordScheduleResult = new TrackRecordScheduleResult();
        trackRecordScheduleResult.setScheduleTime(timeSchedule);

        return CommonResult.success(trackRecordScheduleResult);
    }

    @Override
    public CommonResult<TrackRecordListResult> list(TrackRecordListParam trackRecordListParam) {

        //将时间戳转化为年月日
        long lt = trackRecordListParam.getTime();
        String day = TimeUtil.transform(lt);

        List<DisabuseRecord> disabuseRecordList = disabuseRecordMapper.selectAllDisabuseList();
        List<TrackRecordTime> trackRecordTimeList = trackRecordTimeMapper.selectAll();

        List<PostResult> postResultList = new ArrayList<>();
        List<SelectContent> selectContentList = new ArrayList<>();


        HashSet<PostResult> hs = new HashSet<>();

        //遍历disabuseRecord表
        for (DisabuseRecord temp : disabuseRecordList) {
            String nowDay = TimeUtil.transform(temp.getTime());
            if (day.equals(nowDay)) {
                User user1 = userMapper.selectById(temp.getChildId());
                PostResult postResult = new PostResult();
                postResult.setType(temp.getType());
                postResult.setSolveType(temp.getSolveType());
                postResult.setIsNowSolve(temp.getIsNowSolve());
                postResult.setIsFinish(temp.getIsFinish());
                postResult.setTime(temp.getTime());
                postResult.setDisabuseId(temp.getId());
                postResult.setName(user1.getUsername());
                hs.add(postResult);
            }
        }
        for (PostResult temp : hs) {
            postResultList.add(temp);
        }

        HashSet<SelectContent> hs2 = new HashSet<>();
        //遍历trackRecordTime表
        for (TrackRecordTime temp : trackRecordTimeList) {
            String nowDay = TimeUtil.transform(temp.getTime());
            if (day.equals(nowDay)) {

                HomeInterface homeInterface = homeInterfaceMapper.selectById(temp.getContentId());
                User user1 = userMapper.selectById(temp.getUserId());
                SelectContent selectContent = new SelectContent();
                selectContent.setBookName(homeInterface.getName());
                selectContent.setType(homeInterface.getType());
                selectContent.setTime(temp.getTime());
                selectContent.setName(user1.getUsername());

                hs2.add(selectContent);
            }
        }
        for (SelectContent temp : hs2) {
            selectContentList.add(temp);
        }
        //封装返回结果
        TrackRecordListResult trackRecordListResult = new TrackRecordListResult();
        trackRecordListResult.setPostResultList(postResultList);
        trackRecordListResult.setSelectContentList(selectContentList);

        return CommonResult.success(trackRecordListResult);
    }

    @Override
    public CommonResult<TrackRecordScheduleResult> parentSchedule() {

        Integer parentId = jwtInterceptor.getUserId(request);
        User user = userMapper.selectById(parentId);
        if (user == null) {
            return CommonResult.fail("数据库异常");
        }

        List<Long> timeSchedule = new ArrayList<>();
        List<Relation> disabuseRecordChildIdList = relationMapper.selectByParentId(parentId);

        for (Relation childIdList : disabuseRecordChildIdList) {
            //疑惑的时间列表
            List<DisabuseRecord> disabuseRecordList =
                    disabuseRecordMapper.selectDisabuseListByChildId(childIdList.getChildId());
            HashSet<String> hs = new HashSet<>();
            if (disabuseRecordList.size() != 0) {
                for (DisabuseRecord temp : disabuseRecordList) {
                    long time = temp.getTime();
                    String day = TimeUtil.transform(time);
                    hs.add(day);
                }
//                return CommonResult.fail("数据库异常");
            }



            //听书的时间列表
            List<TrackRecordTime> trackRecordTimeList = trackRecordTimeMapper.selectByUserId(childIdList.getChildId());
            if (trackRecordTimeList.size() != 0) {
//                return CommonResult.fail("数据库异常");
                for (TrackRecordTime temp : trackRecordTimeList) {
                    long time = temp.getTime();
                    String day = TimeUtil.transform(time);
                    hs.add(day);
                }
            }
            if(hs.size()!=0){
                for (String day : hs) {
                    Long time = TimeUtil.transformTurnAll(day);
                    timeSchedule.add(time);
                }
            }
        }
        TrackRecordScheduleResult trackRecordScheduleResult = new TrackRecordScheduleResult();
        trackRecordScheduleResult.setScheduleTime(timeSchedule);

        return CommonResult.success(trackRecordScheduleResult);


    }

    @Override
    public CommonResult<NoData> seedTrackMessage(HttpServletRequest request, TrackMessageParam trackMessageParam) throws Exception {
        Claims claims = TokenUtils.getClaimsFromJwt(request.getHeader("token"));
        Integer userId = (Integer) claims.get("id");
        String userName = userMapper.selectUserNameById(userId);

        //进入短信阶段
        for (SingleTrackMessageParam single : trackMessageParam.getSeedMessageList()) {
            JSONObject template = new JSONObject();
            template.put("name", userName);
            template.put("location", single.getLocation());

            String errorMessage = null;
            SendSmsResponse sendSmsResponse = null;
            com.aliyun.dysmsapi20170525.Client client = AuthenticationServiceImpl.createClient(Constant.accessKeyId
                    , Constant.accessKeySecret);
            com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest =
                    new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                            .setSignName("yuleng的天地")
                            .setTemplateCode("SMS_254720278")
                            .setPhoneNumbers(single.getPhone())
                            .setTemplateParam(String.valueOf(template));
            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
            try {
                sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
            } catch (TeaException error) {
                com.aliyun.teautil.Common.assertAsString(error.message);
            } catch (Exception _error) {
                TeaException error = new TeaException(_error.getMessage(), _error);
                errorMessage = error.message;
            }
            if (errorMessage == null && "OK".equals(Objects.requireNonNull(sendSmsResponse).body.message)) {
                log.info(single.getPhone() + "短信发送成功");
            } else if (errorMessage != null) {
                return CommonResult.fail(errorMessage);
            } else {
                return CommonResult.fail(sendSmsResponse.body.message);
            }
        }

        return CommonResult.success();
    }

}
